package LearnReflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class LearnReflection {

	public static void main(String[] args) {
		Person person = new Person("楼宗", 1234, 1.0d);
		reflect(person);

		System.out.println("修改后:" + person.getName());
	}

	@SuppressWarnings("unused")
	public static void reflect(Object obj) {
		//获得类对象
		//1.
		Class<? extends Object> classType = obj.getClass();
		
		//2.根据类名返回类对象
		Class<People> classType2 = People.class;
		
		//3.搜索这个类
		try {
			
			Class<?> classType3 = Class.forName("Person");
			
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		
		//实例化
		//1.
		try {
			People newperson =(People) classType.newInstance();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		
		//2.
		try {
			classType.getConstructors()[0].newInstance("结衣",520,172.0);
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}
		
		
		
		
		Field[] fields = classType.getDeclaredFields();
		Field[] allFields = classType.getFields();
		System.out.println(Arrays.toString(fields));
		System.out.println(Arrays.toString(allFields));

		for (Field f : fields) {
			f.setAccessible(true);
			try {
				if ("name".equals(f.getName())) {
					f.set(obj, "YuiAragaki");
				}
				System.out.println(f.getName() + ":" + f.get(obj));
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}

		System.out.println("--------------");
		System.out.println("方法:");
//		for (Method m : classType.getMethods()) {
//			System.out.println(m.getName());
//			if ("setName".equals(m.getName())) {
//				try {
//					m.invoke(obj, "新垣结衣");
//				} catch (IllegalAccessException e) {
//					e.printStackTrace();
//				} catch (IllegalArgumentException e) {
//					e.printStackTrace();
//				} catch (InvocationTargetException e) {
//					e.printStackTrace();
//				}
//			}
//		}

	}
}
